<template>
  <div class="pay-list" :class="payListStyle">
    <div class="pay-radio-list">
      <label class="pay-radio paypal">
        <span class="pay-label">
          <svg-icon icon-class="logoPaypal"></svg-icon>
          PayPal
        </span>
        <input
          class="radio"
          type="radio"
          v-model="payMode"
          value="5"
          name="payMode"
        />
      </label>
      <!-- <label class="pay-radio Googlepay">
        <span class="pay-label">
          <svg-icon icon-class="logoGooglepay"></svg-icon>
          Googlepay
        </span>
        <input
          class="radio"
          disabled
          type="radio"
          v-model="payMode"
          value="6"
          name="payMode"
        />
      </label> -->
      <label class="pay-radio Applepay">
        <span class="pay-label">
          <svg-icon class="icon_apple" icon-class="appleIcon"></svg-icon>
          Applepay
        </span>
        <input
          class="radio"
          type="radio"
          v-model="payMode"
          value="4"
          name="payMode"
        />
      </label>
    </div>
    <ul class="pay-active-list">
      <li
        @click="payMode = item.value"
        v-for="item of payModeList"
        :key="item.value"
        :class="{ active: payMode === item.value }"
      >
        <svg-icon :class="item.iconClass" :icon-class="item.icon"></svg-icon>
        <span class="pay-desc" v-text="item.text"></span>
      </li>
    </ul>
    <ul class="tips" v-if="payListStyle === 'coins-pay-list'">
      <h4>Tips:</h4>
      <li>1.Coins can be used to unlock chapters.</li>
      <li>
        2.Purchased Coins don't expire, are non-transferrable, and can be used
        for reading.
      </li>
      <li>
        3.If you encounter problems with recharging, you can
        <span @click="toPage('sendFeedback')" class="feedback">feedback</span>
        to customer service.
      </li>
    </ul>
    <ul class="tips" v-if="payListStyle === 'premium-pay-list'">
      <h4>Tips:</h4>
      <li>1.Effective immediately after opening.</li>
      <li>
        2.lf your Premium has not expired yet, andyou choose to renew, the
        extention will begin right afterthe expriation day. Please feel free to
        renew.
      </li>
      <li>
        3.If you encounter problems with recharging, you can
        <span @click="toPage('sendFeedback')" class="feedback">feedback</span>
        to customer service.
      </li>
    </ul>
    <div class="payNow-box">
      <div
        class="pay-now"
        :payNow-content="
          currentCard.rechargeId
            ? `Total ${currentCard.conversionCoin + currentCard.giveCoin} = ${
                currentCard.conversionCoin
              }Coins${
                currentCard.giveCoin
                  ? ' + ' + currentCard.giveCoin + 'Coins'
                  : ''
              }`
            : `Free Reading For Premiun`
        "
      >
        <el-button
          id="paypal-button"
          v-text="
            'Pay Now us$' + (currentCard.rechargeSum || currentCard.price || 0)
          "
          @click="createOrder(currentCard)"
        ></el-button>
      </div>
      <!-- <PayPal
        :amount="
          currentCard.rechargeSum
            ? currentCard.rechargeSum + ''
            : currentCard.price + ''
        "
        currency="USD"
        :client="credentials"
        env="sandbox"
        :button-style="buttonStyle"
        @payment-authorized="paymentAuthorized"
        @payment-completed="paymentCompleted"
        @payment-cancelled="paymentCancelled"
      >
      </PayPal> -->
    </div>
    <!-- 点击付款弹窗 -->
    <div class="popup-box" v-show="isRechargeBox">
      <div class="paypal-box">
        <span class="close-icon" @click="isRechargeBox = false">
          <svg-icon icon-class="loginCloseIcon"></svg-icon>
        </span>
        <div id="recharge-box" v-if="isRechargeBox">
          <apple-pay-button
            v-if="payMode == 4"
            buttonstyle="black"
            type="plain"
            locale="en"
          ></apple-pay-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapGetters } from "vuex";
import { loadScript } from "@paypal/paypal-js";
// import PayPal from "vue-paypal-checkout";
export default {
  props: {
    payListStyle: {
      type: String,
      default: "coins-pay-list",
    },
    currentCard: {
      type: Object,
    },
  },
  data() {
    return {
      payMode: 5, //支付方式
      payModeList: [
        {
          icon: "logoPaypal",
          iconClass: "icon_paypal",
          value: 5,
          text: "PayPal",
        },
        // {
        //   icon: "logoGooglepay",
        //   iconClass: "icon_Googlepay",
        //   value: 6,
        //   text: "Googlepay",
        // },
        {
          icon: "appleIcon",
          iconClass: "icon_apple",
          value: 4,
          text: "Applepay",
        },
      ],
      // credentials: {
      //   //填写沙箱环境client_id
      //   sandbox:
      //     "AdYXcJST_chgfAHaz4gozY-oK2MoO8QryXqSerdBOq7AU254HC9GL_EDccAhmo7sbjzoEetP6IJlSP9L",
      //   // 填写线上环境client_id
      //   production:
      //     "AdYXcJST_chgfAHaz4gozY-oK2MoO8QryXqSerdBOq7AU254HC9GL_EDccAhmo7sbjzoEetP6IJlSP9L",
      // },
      // //付款按钮样式
      // buttonStyle: {
      //   label: "pay", //checkout
      //   size: "responsive",
      //   shape: "rect",
      //   color: "gold", // gold | blue | silver | black
      // },
      clientId:
        process.env.VUE_APP_MODE === "production"
          ? "AfJ-F6EHxaNS02dMlda-vQw2zBqdPEUNpjBtCFJf-wQDJsltaorA0KTio73ccPbM9cT22iB8ZGnJNooh"
          : "AeEX1PNMNaP3RuV8JTBMznAhs_gOfFwloG6SG3TiQh1_MBj0YZHlWYPKvdjH1q5GrpPSApZka-bOmhF2",
      outOrderNo: "", //三方订单号
      orderNo: "", // 本站订单号
      isRechargeBox: false,
    };
  },
  components: {
    // PayPal,
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    ...mapMutations({
      // setShowPopup: "SET_SHOW_POPUP",
      setCurrentDialog: "SET_CURRENT_DIALOG",
    }),
    // onLoadSDK(sdk){
    //   let po = document.createElement("script");
    //   po.type = "text/javascript";
    //   po.async = true;
    //   if(sdk == 'paypal') {
    //     po.src = ""
    //   }

    // },
    // paypal支付
    // paymentAuthorized(data) {
    //   // 授权完成的回调，可以拿到订单id
    //   console.log("授权完成");
    //   console.log(data);
    //   this.orderId = data.orderID;
    //   this.createOrder();
    // },
    // paymentCompleted(data) {
    //   // 用户支付完成的回调，可以拿到订单id
    //   console.log("用户支付完成");
    //   console.log(data);
    //   this.payPalNotify(this.orderId);
    // },
    // paymentCancelled(data) {
    //   // 用户取消交易的回调
    //   console.log("用户取消交易");
    //   console.log(data);
    // },

    // 创建订单
    async createOrder(item) {
      console.log(item)
      if (this.userInfo) {
        let params = {
          bookId: "", //看过后充值的书籍id
          gainUserId: this.userInfo ? this.userInfo.authorId : "", //被充值用户ID
          orderType: item.rechargeId ? 1 : item.vipId ? 3 : null, //1 书币充值 ; 2 plus会员充值；3 premium会员充值
          payType: this.payMode, //支付方式 1 微信； 2 支付宝；3 QQ钱包 4 苹果支付 5 PayPal支付 6 google内购
          rechargeId: item.rechargeId, //书币充值套餐ID
          vipId: item.vipId, //会员套餐Id
        };
        let res = await this.$api.home.createOrder(params);
        if (res.code === 1) {
          // window.open(res.source.outOrderNo);
          let orderNo = res.source.orderId;
          let token = res.source.Id;
          let that = this;
          this.isRechargeBox = true;
          // 苹果支付
          if (this.payMode == 4) {
            if (!window.ApplePaySession) {
              return;
            }
            // Define ApplePayPaymentRequest
            const request = {
              countryCode: "US",
              currencyCode: "USD",
              merchantCapabilities: ["supports3DS"],
              supportedNetworks: ["visa", "masterCard", "amex", "discover"],
              total: {
                label: item.text,
                type: "final",
                amount: item.rechargeSum || item.price,
              },
            };

            // Create ApplePaySession
            const session = new window.ApplePaySession(3, request); //Apple Pay 版本3
            console.log(session);

            session.onvalidatemerchant = async (event) => {
              console.log(event);
              // 调用您自己的服务器请求一个新的商业会话
              const merchantSession = await window.validateMerchant();
              session.completeMerchantValidation(merchantSession);
            };

            session.onpaymentmethodselected = (event) => {
              // 根据所选的支付方式定义ApplePayPaymentMethodUpdate
              // 不需要更新或错误，传递一个空对象
              const update = {};
              session.completePaymentMethodSelection(update);
            };

            session.onshippingmethodselected = (event) => {
              // 根据所选的配送方法定义ApplePayShippingMethodUpdate
              // 不需要更新或错误，传递一个空对象
              const update = {};
              session.completeShippingMethodSelection(update);
            };

            session.onshippingcontactselected = (event) => {
              // 根据所选的发货联系人定义ApplePayShippingContactUpdate
              const update = {};
              session.completeShippingContactSelection(update);
            };

            session.onpaymentauthorized = (event) => {
              // 定义 ApplePayPaymentAuthorizationResult
              const result = {
                status: window.ApplePaySession.STATUS_SUCCESS,
              };
              session.completePayment(result);
            };

            session.oncouponcodechanged = (event) => {
              // 定义 ApplePayCouponCodeUpdate
              const newTotal = window.calculateNewTotal(event.couponCode);
              const newLineItems = window.calculateNewLineItems(event.couponCode);
              const newShippingMethods = window.calculateNewShippingMethods(
                event.couponCode
              );
              const errors = window.calculateErrors(event.couponCode);

              session.completeCouponCodeChange({
                newTotal: newTotal,
                newLineItems: newLineItems,
                newShippingMethods: newShippingMethods,
                errors: errors,
              });
            };

            session.oncancel = (event) => {
              // WebKit取消付款
            };

            session.begin();
          } else if (this.payMode == 5) {
            // PayPal支付
            loadScript({
              "client-id": this.clientId,
            })
              .then((paypal) => {
                paypal
                  .Buttons({
                    // data, actions
                    createOrder: function () {
                      // This function sets up the details of the transaction, including the amount and line item details.
                      return token;
                    },
                    onApprove: function (data, actions) {
                      return actions.order.capture().then(function (details) {
                        // 支付完成的回调.
                        that.isRechargeBox = false;
                        // alert(
                        //   "Transaction completed by " +
                        //     details.payer.name.given_name
                        // );
                        // Call your server to save the transaction
                        that.payPalNotify(orderNo, details.id);
                        return "";
                      });
                    },
                    onCancel: function () {
                      that.isRechargeBox = false;
                      this.$message({
                        message: "Payment Canceled",
                        duration: "1500",
                        type: "warning",
                      });
                    },
                    onError: function () {
                      that.isRechargeBox = false;
                      this.$message({
                        message: "Payment Failded",
                        duration: "1500",
                        type: "error",
                      });
                    },
                  })
                  .render("#recharge-box")
                  .catch((error) => {
                    console.error("failed to render the PayPal Buttons", error);
                  });
              })
              .catch((error) => {
                console.error("failed to load the PayPal JS SDK script", error);
              });
          }
        }
      } else {
        this.setCurrentDialog({ current: "login" });
        // this.setShowPopup(true);
      }
    },
    // 贝宝支付二次验证
    async payPalNotify(orderNo, outOrderNo) {
      let params = {
        orderNo, //本站订单号
        orderType: this.currentCard.rechargeId
          ? 1
          : this.currentCard.vipId
          ? 3
          : null, //1 书币充值 ; 2 plus会员充值；3 premium会员充值
        outOrderNo, //paypal订单号
        // userId: this.userInfo.authorId, //用户id
      };
      let res = await this.$api.home.payPalNotify(params);
      // console.log(res);
      if (res.code === 1) {
        this.$message({
          message: "Payment Successful",
          duration: "1500",
          type: "success",
        });
        this.$emit("recharge", res.source);
      } else {
        this.$message({
          message: "Payment Failded",
          duration: "1500",
          type: "error",
        });
      }
    },
    // 页面跳转
    toPage(name) {
      this.setCurrentDialog(null);
      this.$router.push({
        name,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
apple-pay-button {
  --apple-pay-button-width: 150px;
  --apple-pay-button-height: 30px;
  --apple-pay-button-border-radius: 3px;
  --apple-pay-button-padding: 0px 0px;
  --apple-pay-button-box-sizing: border-box;
}

.pay-list {
  .icon_apple {
    background: #000000;
    border-radius: 6px;
  }
  &.coins-pay-list,
  &.premium-pay-list {
    margin-top: 14px;
    .pay-radio-list {
      .pay-radio {
        width: 100%;
        display: flex;
        cursor: pointer;
        justify-content: space-between;
        align-items: center;
        &:not(:first-child) {
          margin-top: 18px;
        }
        // &.Googlepay {
        //   margin-top: 18px;
        //   // 禁用googlepay
        //   .pay-label {
        //     opacity: 0.3;
        //   }
        // }
        .pay-label {
          display: flex;
          align-items: center;
          font-size: 18px;
          color: #000000;
          font-weight: 500;
          font-family: Poppins-Medium, Poppins;
          .svg-icon {
            width: 40px;
            height: 40px;
            margin-right: 16px;
          }
        }
        .radio {
          width: 22px;
          height: 22px;
        }
      }
    }
    .tips {
      margin-top: 45px;
      color: #999999;
      > h4 {
        font-size: 16px;
        font-family: Poppins-Medium, Poppins;
        font-weight: 500;
        line-height: 26px;
      }
      li {
        font-size: 14px;
        margin-top: 4px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        line-height: 20px;
        .feedback {
          cursor: pointer;
          color: #e86472;
          text-decoration: underline;
        }
      }
    }
    .pay-active-list {
      display: none;
    }
  }
  &.reader-pay-list {
    margin-top: 28px;
    .pay-radio-list {
      display: none;
    }
    .pay-active-list {
      display: flex;
      li {
        width: 160px;
        height: 85px;
        cursor: pointer;
        box-sizing: border-box;
        margin-right: 28px;
        border-radius: 16px;
        border: 2px solid #eeeeee;
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: space-between;
        &.active {
          border-color: #e86472;
          span.pay-desc {
            color: #e86472;
            background: #fae0e3;
          }
        }
        .svg-icon {
          width: 40px;
          height: 40px;
          margin: auto 0;
        }
        span.pay-desc {
          width: 100%;
          height: 32px;
          font-size: 18px;
          line-height: 32px;
          color: #999999;
          font-weight: 500;
          text-align: center;
          font-family: Poppins-Medium, Poppins;
          background: #eeeeee;
          border-radius: 0px 0px 16px 16px;
        }
      }
    }
    .payNow-box {
      height: 109px;
      margin-top: 53px;
      > .pay-now {
        height: 109px;
        &::before {
          content: attr(payNow-content);
          width: 100%;
          height: 32px;
          font-size: 14px;
          line-height: 32px;
          text-align: center;
          font-weight: 500;
          display: block;
          color: #e86472;
          font-family: PingFangSC-Medium, PingFang SC;
          background: rgba(232, 100, 114, 0.1);
        }
      }
    }
  }
  > .payNow-box {
    width: 100%;
    height: 77px;
    margin-top: 32px;
    > .pay-now {
      width: 100%;
      height: 77px;
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      z-index: 998;
      .el-button {
        width: 100%;
        height: 77px;
        border-radius: 0;
        color: #ffffff;
        font-size: 22px;
        font-weight: 500;
        border-width: 0;
        background: linear-gradient(270deg, #e25178 0%, #f16d56 100%);
      }
    }
  }
  > .popup-box {
    width: 100%;
    height: 100%;
    z-index: 999;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    .paypal-box {
      width: 520px;
      height: 320px;
      background: #fff;
      border-radius: 16px;
      position: relative;
      .close-icon {
        cursor: pointer;
        .svg-icon {
          width: 48px;
          height: 48px;
          position: absolute;
          top: 0;
          right: 0;
        }
      }
      #recharge-box {
        width: 100%;
        height: 100%;
        padding: 0 30px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
